package com.jiangyan.hookplus.common

import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
import okhttp3.OkHttpClient
import okhttp3.Request

class Request {
    /**
     * 获取有道云文档内的数据
     * 将数据从字符串转换map<*,*>在转换string？再转换 List<Pair<String, String>>
     * **/
    private fun getNestedValue(url: String): String {
        val objectMapper = ObjectMapper().registerKotlinModule()
        val client = OkHttpClient()
        val request = Request.Builder().url(url).build()
        val response = client.newCall(request).execute()
        val responseBody: String = response.body?.string() ?: ""
        if (response.isSuccessful) {
            val jsonObjects = objectMapper.readValue(responseBody, Map::class.java)
            val entryValue = jsonObjects["entry"]
            if (entryValue is Map<*, *>) {
                val nestedValue = entryValue["summary"]
                return nestedValue.toString()
            }
        } else {
            println("Request failed with response code: ${response.code}")
        }
        return url
    }


    //将接口响应格式转化为List<Pair<String, String>>
    private fun convertStringToListPairs(string: String): List<Pair<String, String>> {
        val pairs = string.split(",") // 按逗号分隔字符串，得到每个键值对
        val resultList: MutableList<Pair<String, String>> = mutableListOf()

        for (pair in pairs) {
            val keyValue = pair.split("*") // 按冒号分隔键值对，得到键和值
            val key = keyValue[0]
            val value = keyValue[1]
            val pairObject = Pair(key, value)
            resultList.add(pairObject)
        }

        return resultList
    }

    fun getListValue(url: String): MutableList<Pair<String, String>> {
        val nestedValue = getNestedValue(url)
        val listPairs = convertStringToListPairs(nestedValue)
        val items = mutableListOf<Pair<String, String>>(
        )
        for (pair in listPairs) {
            items.add(Pair(pair.first, pair.second))
        }
        return items
    }

}

fun main() {
}